<template>
<!-- 关联答案 -->
  <div>
      <!-- 基本信息 -->
    <div class="policy-main circulationInfo" >
        <div class="base-mian-cell-title mt clearfix">
          <div class="left fl">
            <i></i>
            <span class="tips">基本信息</span>
          </div>
        </div>
        <el-form ref="form" :model="form" label-width="150px" style="overflow: hidden;padding: 20px 85px 0 30px;">
            <el-col :span="8" class="common-box">
              <el-form-item label="问题编号：">
                <el-input disabled v-model="form.questionCode" placeholder="请输入分类编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="common-box">
              <el-form-item label="父问题编号：">
                <el-input disabled v-model="form.parentCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="common-box">
              <el-form-item label="适用人群：">
                <el-select v-model="form.forPeople" disabled placeholder="请选择适用人群">
                  <el-option
                    v-for="item in crowdOptions"
                    :key="item.paramCode"
                    :label="item.paramName"
                    :value="item.paramCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16" class="common-box">
              <el-form-item label="关联疾病：">
                <el-input disabled v-model="form.diseaseName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="common-box">
              <el-form-item label="关联险类：">
                <el-select disabled v-model="form.insuranceCategoryCode" placeholder="请选择关联险类">
                  <el-option
                    v-for="item in insureOptions"
                    :key="item.paramCode"
                    :label="item.paramName"
                    :value="item.paramCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="common-box">
              <el-form-item label="是否有效：">
                <el-switch disabled class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="form.isValid"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="common-box">
              <el-form-item label="是否多选：">
                <el-switch disabled class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="form.isMultipleChoices"></el-switch>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="8" class="common-box">
              <el-form-item label="是否必答：">
                <el-switch disabled class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="form.isMustAnswer"></el-switch>
              </el-form-item>
            </el-col> -->
            <el-col :span="24" class="common-box">
              <el-form-item label="问题内容：">
                <el-input disabled type="textarea" :rows="3" v-model="form.content" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
        </el-form>
    </div>

    <!-- 答案信息 -->
    <div class="policy-main circulationInfo" >
      <div class="base-mian-cell-title mt clearfix">
        <div class="left fl">
          <i></i>
          <span class="tips">答案信息</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <el-row style="margin-top: 15px;margin-left: 10px;">
        <el-col :span="24" class="pb15 pt5">
          <el-button
            type="danger"
            icon="el-icon-circle-plus-outline"
            size="mini"
            style="margin-left: 10px"
            plain
            @click="add()"
            > 新增
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-collection"
            size="mini"
            style="margin-left: 10px"
            plain
            @click="save()"
            > 保存
          </el-button>
        </el-col>
      </el-row>


      <!--基本信息列表  -->
      <div class="costbox">
        <el-table :data="dataList" highlight-current-row header-cell-class-name="table-header-class" style="width: 100%">
          <!-- <el-table-column type="index" label="序号" width="80"></el-table-column> -->
          <el-table-column align="center" type="index" width="80" label="序号"></el-table-column>
          <el-table-column align="center" label="答案编号" prop="answerCode" min-width="140" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="答案内容" prop="contentText" min-width="160" show-overflow-tooltip></el-table-column>
          
          <el-table-column align="center" label="是否结束" prop="isEnd" width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.isEnd == 1 ? '是':'否' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="核保结论" prop="underwriteConclusion" width="140" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ getShowConclusion(scope.row.underwriteConclusion) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="下一个问题" prop="nextQuestion" min-width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ getShowNextQuestion(scope.row) }}</span>
            </template>  
          </el-table-column>  
          <el-table-column
            align="center"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" icon="el-icon-edit-outline" @click="edit(scope.row,scope.$index)"></el-button>
              <el-button type="text" size="small" icon="el-icon-delete" @click="del(scope.row,scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog :title="handleType == 'add'?'新增答案':'编辑答案'" v-if="answerVisible" :visible.sync="answerVisible" :close-on-click-modal="false" :modal-append-to-body="false" width="60%" center class="dialog">
      <el-form ref="answerForm" :model="answerForm" label-width="150px" :rules="answerRules" style="overflow: hidden">
        <el-col :span="12" class="common-box">
          <el-form-item label="答案编号：" prop="answerCode">
            <el-input :disabled="handleType == 'edit'" v-model="answerForm.answerCode" placeholder="请输入答案编号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box">
          <el-form-item label="答案类型：" prop="dataType">
            <el-select v-model="answerForm.dataType" placeholder="请选择答案类型" clearable>
              <el-option
                v-for="item in answerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box">
          <el-form-item label="是否结束：" prop="isEnd">
            <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="answerForm.isEnd" @change="endFlagChange"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box">
          <el-form-item label="核保结论：">
            <el-select :disabled="answerForm.isEnd!==1" v-model="answerForm.underwriteConclusion" placeholder="请选择核保结论" clearable>
              <el-option
                v-for="item in conclusionOptions"
                :key="item.paramCode"
                :label="item.paramName"
                :value="item.paramCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="common-box">
          <el-col :span="12" class="common-box">
            <el-form-item label="下一个问题：">
              <el-select :disabled="answerForm.isEnd==1" v-model="answerForm.nextQuestionCode" placeholder="请选择" clearable>
                <el-option
                  v-for="item in nextQuestionOption"
                  :key="item.questionCode"
                  :label="item._content"
                  :value="item.questionCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-button :disabled="answerForm.isEnd==1" type="danger" icon="el-icon-circle-plus-outline" size="mini" style="margin-left: 10px" plain @click="addQuestion()">新增问题</el-button>
        </el-col>
        <el-col :span="24" class="common-box">
          <el-form-item label="答案内容：">
            <el-input type="textarea" :rows="3" v-model="answerForm.contentText" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
      </el-form>
      
      <!-- 内层新增问题弹窗 -->
      <el-dialog
        title="新增问卷"
        v-if="questionVisible"
        :visible.sync="questionVisible"
        :close-on-click-modal="false"
        width="60%"
        center
        class="dialog"
        append-to-body
        >
        <el-form ref="questionForm" :model="questionForm" label-width="150px" :rules="rules" style="overflow: hidden">
          <el-col :span="12" class="common-box">
            <el-form-item label="问题编号：" prop="questionCode">
              <el-input v-model="questionForm.questionCode" placeholder="请输入问题编号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="common-box">
            <el-form-item label="父问题编号：">
              <el-input disabled v-model="questionForm.parentCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="common-box">
            <el-form-item label="关联疾病：">
              <el-input disabled v-model="questionForm.diseaseName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="common-box" style="height:40px">
            <el-form-item label="适用人群：" prop="forPeople">
              <el-select v-model="questionForm.forPeople" placeholder="请选择适用人群" clearable>
                <el-option
                  v-for="item in crowdOptions"
                  :key="item.paramCode"
                  :label="item.paramName"
                  :value="item.paramCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="common-box">
            <el-form-item label="是否有效：" prop="isValid">
              <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="questionForm.isValid"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="common-box" style="height:40px">
            <el-form-item label="关联险类：" prop="insuranceCategoryCode">
              <el-select v-model="questionForm.insuranceCategoryCode" placeholder="请选择关联险类" clearable>
                <el-option
                  v-for="item in insureOptions"
                  :key="item.paramCode"
                  :label="item.paramName"
                  :value="item.paramCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12" class="common-box">
            <el-form-item label="是否多选：" prop="isMultipleChoices">
              <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="questionForm.isMultipleChoices"></el-switch>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" class="common-box">
            <el-form-item label="是否必答：" prop="isMustAnswer">
              <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="questionForm.isMustAnswer"></el-switch>
            </el-form-item>
          </el-col> -->
          <el-col :span="24" class="common-box">
            <el-form-item label="问题内容：" prop="content">
              <el-input type="textarea" :rows="3" v-model="questionForm.content" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="common-box">
            <el-form-item label="备注：">
              <el-input type="textarea" :rows="3" v-model="questionForm.remark" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="questionSave">保 存</el-button>
          <el-button @click="questionReset">取 消</el-button>
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="answerSave">保 存</el-button>
        <el-button @click="answerReset">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getParamPageListApi, getByIdQuestionApi, getQuestionListApi, insertOrUpdateQuestionApi, insertOrUpdateAnswerApi} from "@/api/setting/maintain/askMaintenance"; //调接口
export default {
  data() {
    return {
      dataList:[],
      form: {},
      crowdOptions:[],//适用人群
      insureOptions:[],//关联险类
      handleType: 'add',

      // 答案
      answerVisible: false,
      answerForm: {
        questionCode: '',
        answerCode: '',
        dataType: '',
        isEnd: 0,
        underwriteConclusion: '',
        nextQuestionCode:'',
        contentText: ''
      },
      answerTypeOptions: [{  //答案类型
        value: '0',
        label: 'String'
      }, {
        value: '1',
        label: 'Int'
      }],
      conclusionOptions:[],//核保结论
      nextQuestionOption: [], //下一个问题

      answerRules: {
        answerCode: [
          { required: true, message: '请输入答案编号', trigger: 'blur' },
        ],
        dataType: [
          { required: true, message: '请选择答案类型', trigger: 'change' }
        ],
        isEnd: [
          { required: true, message: '请选择是否结束', trigger: 'change' }
        ],
      },

      // 问题
      questionVisible: false,
      answerEditIdx: 0, //点击答案列表编辑按钮的下标
      answerDelList: [], //答案列表删除的数据集合
      questionForm: {
        questionCode: '',
        parentCode: '',
        diseaseName: '',
        diseaseCode: '',
        forPeople: '',
        insuranceCategoryCode:'',
        isMultipleChoices: 0,
        isMustAnswer: 1,
        content: '',
        remark: '',
        isValid: 1,
        isEnd: 0,
      },
      rules: {
        questionCode: [
          { required: true, message: '请输入问题编号', trigger: 'blur' },
        ],
        forPeople: [
          { required: true, message: '请选择适用人群', trigger: 'change' }
        ],
        insuranceCategoryCode: [
          { required: true, message: '请选择关联险类', trigger: 'change' }
        ],
        isValid: [
          { required: true, message: '请选择是否有效', trigger: 'change' }
        ],
        isMultipleChoices: [
          { required: true, message: '请选择是否多选', trigger: 'change' }
        ],
        /* isMustAnswer: [
          { required: true, message: '请选择是否必答', trigger: 'change' }
        ], */
        content: [
          { required: true, message: '请输入问题内容', trigger: 'blur' },
        ],
      },
    }
  },
  watch:{
   $route(to,from){
     if(from.name == 'relationAnswer') {
       this.questionVisible = false
       this.answerVisible = false
     }
    }
  },
  created(){
    this.getCrowdOptionsORConclusionOptions('forPeople')
    this.getCrowdOptionsORConclusionOptions('underwriteConclusion')
    this.getInsureOptions()
    this.getNextQuestion()
  },
  mounted(){
    this.searchClick()
  },
  methods: {
    // 获取适用人群数据
    getCrowdOptionsORConclusionOptions(paramGroupCode){
      let params = {
        pageNum: 1, //当前页
        pageSize: 999, //每页数
        paramGroupCode,
        isValid: 1
      }
      getParamPageListApi(params).then((res) => {
        if (res.resultCode === 0) {
          let {list} = res.data
          if(paramGroupCode == 'forPeople') this.crowdOptions = list || []
          else this.conclusionOptions = list || []
        }
      })
    },
    // 获取险类数据
    getInsureOptions(){
      let params = {
        pageNum: 1, //当前页
        pageSize: 999, //每页数
        paramGroupCode: 'category',
        isValid: 1
      }
      getParamPageListApi(params).then((res) => {
        if (res.resultCode === 0) {
          let {list} = res.data
          this.insureOptions = list || []
        }
      })
    },
    // 根据疾病code获取问题列表
    getNextQuestion(){
      let params = {
        pageNum: 1, //当前页
        pageSize: 999, //每页数
        diseaseCode: this.$route.query.diseaseCode,
      }
      getQuestionListApi(params).then((res) => {
        if (res.resultCode === 0) {
          this.nextQuestionOption = res.data || []
          if(this.nextQuestionOption.length){
            this.nextQuestionOption.forEach(item=>{
              item._content = item.questionCode + '-' + item.content
            })
          }
        }
      })
    },
    // 匹配核保结论
    getShowConclusion(val){
      let conclusion = '-'
      if(val){
        this.conclusionOptions.forEach(item=>{
          if(item.paramCode == val) conclusion = item.paramName
        })
      }
      return conclusion
    },
    // 表格显示下一个问题
    getShowNextQuestion(row){
      let nextQuestion = '-'
      if(row.nextQuestion && row.nextQuestion.questionCode){
        nextQuestion = `${row.nextQuestion.questionCode}-“${row.nextQuestion.content}”`
      }
      return nextQuestion
    },
    add(){
      this.answerForm = {
        questionCode: this.form.questionCode,
        answerCode: '',
        dataType: '',
        isEnd: 0,
        underwriteConclusion: '',
        nextQuestionCode:'',
        contentText: ''
      },
      this.handleType = 'add'
      this.answerVisible = true
    },

    // 大页面保存
    save(){
      if(this.form.isEnd == 1){
        this.$message.closeAll()
        this.$message.warning('已结束的问题不能关联答案！')
        return
      }
      let ids = []
      if(this.answerDelList.length){
        ids = this.answerDelList.filter(item=> item.id).map(val=> val.id)
      }
      let param = {
        answers: this.dataList,
        ids
      }
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      insertOrUpdateAnswerApi(param).then((res) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode === 0) {
          this.$message.success('保存成功')
          this.$router.go(-1);
        }
      })
    },

    edit(row,idx){  //编辑
      this.answerForm = JSON.parse(JSON.stringify(row))
      this.answerEditIdx = idx
      this.handleType = 'edit'
      this.answerVisible = true
    },
    del(row,idx){  //删除
      this.$confirm('是否删除该条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.answerDelList.push(row)
        this.dataList.splice(idx,1); 
      }).catch(() => {
      });
    },
    // 获取列表数据
    searchClick(){
      this.$store.dispatch("loading/CHANGE_LOADING", true);
       getByIdQuestionApi({id:this.$route.query.id}).then((res) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode === 0) {
          this.form = res.data
          this.dataList = res.data.children && res.data.children.length ? JSON.parse(JSON.stringify(res.data.children)) : []
        }
      }).catch((err) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
      });
    },
    // 答案弹窗是否结束switch状态改变时触发
    endFlagChange(val){
      if(val==1){
        this.answerForm.nextQuestionCode = ''
        this.answerForm.nextQuestion = null
      }
      else this.answerForm.underwriteConclusion = ''
    },
    // 点击新增答案弹窗的保存按钮
    answerSave(){
      this.$refs['answerForm'].validate((valid) => {
        if (valid) {
          if(this.answerForm.isEnd && !this.answerForm.underwriteConclusion){
            this.$message.warning('请选择核保结论！')
            return
          }
          if(!this.answerForm.isEnd && !this.answerForm.nextQuestionCode){
            this.$message.warning('请选择下一个问题！')
            return
          }
          if(this.answerForm.nextQuestionCode){
            this.nextQuestionOption.forEach(item=>{
              if(item.questionCode == this.answerForm.nextQuestionCode) this.answerForm.nextQuestion = item
            })
          }
          //新增答案
          if(this.handleType == 'add') this.dataList.push(this.answerForm)
          // 编辑答案
          else this.dataList.splice(this.answerEditIdx,1,this.answerForm)
          this.answerReset()
        } else {
          return
        }
      })
    },
    // 点击新增答案弹窗的取消按钮
    answerReset(){
      this.answerVisible = false
    },
    // 点击新增问题按钮
    addQuestion(){
      this.questionForm = {
        questionCode: '',
        parentCode: this.form.questionCode,
        diseaseName: this.form.diseaseName,
        diseaseCode: this.form.diseaseCode,
        forPeople: '',
        insuranceCategoryCode:'',
        isMultipleChoices: 0,
        isMustAnswer: 1,
        content: '',
        remark: '',
        isValid: 1,
        isEnd: 0,
      }
      this.questionVisible = true
    },
    // 点击新增答案弹窗的保存按钮
    questionSave(){
      this.$refs['questionForm'].validate((valid) => {
        if (valid) {
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          insertOrUpdateQuestionApi(this.questionForm).then((res) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
            if (res.resultCode === 0) {
              this.$message.success('保存成功')
              this.getNextQuestion()
              this.questionReset()
            }
          })
        } else {
          return false;
        }
      });
    },
    // 点击新增答案弹窗的取消按钮
    questionReset(){
      this.questionVisible = false
    },
   
  },
};
</script>

<style lang = "less" scoped>
.policy-main {
  background: #fff;
  .base-mian-cell-title {
    margin: 0px 20px;
    padding: 0 20px;
    height: 48px;
    line-height: 48px;
    border-bottom: 1px solid #e1e1e1;
    overflow: hidden;
    .left {
      .line {
        color: #f76767;
        float: left;
      }
      .tips {
        margin-left: 10px;
        font-weight: bold;
        float: left;
      }
      i{
        width: 2px;
        height: 16px;
        float: left;
        background: red;
        margin-top: 17px;
      }
      .input{
        display: inline-block;
        border:1px solid #e1e1e1;
        line-height: 36px;
        background-color: #fff;
        margin: 0 20px;
        width: 200px;
        padding-left: 15px;
      }
      .el-input {
        /* width: 50%; */
        margin-left: 20px;
        .el-input__inner {
          height: 34px;
          width: 180%;
        }
      }
    }
    .right {
      padding: 0 10px;
      cursor: pointer;
      .el-icon-arrow-down {
        color: #999;
        font-size: 24px;
        line-height: 48px;
      }
      .transform {
        transform: rotate(270deg);
      }
    }
  }
  .mt{
    margin-top: 0px;
  }

}

/deep/.el-table thead tr:nth-of-type(2){
  display: none;
}

.costbox{
    margin: 20px 20px 0 20px;
    padding-bottom: 20px;
    .colsty{
        background-color: #f9f9f9;
        line-height: 40px;
        border: 1px solid #DCDFE6;
        border-radius: 4px;
    }
  }

  /deep/ .col-reset .el-form-item__label{
    width: 85px !important;
    text-align: left !important;
  }
  /deep/ .col-reset .el-form-item__content{
    margin-left: 82px !important;
  }


/deep/ .tableScopeSwitch .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
}
/*打开时文字位置设置*/
/deep/ .tableScopeSwitch .el-switch__label--right {
    z-index: 1;
    right: -10px;
}
/*关闭时文字位置设置*/
/deep/ .tableScopeSwitch .el-switch__label--left {
    z-index: 1;
    left: 20px;
}
/*显示文字*/
/deep/ .tableScopeSwitch .el-switch__label.is-active {
    display: block;
}
/deep/ .tableScopeSwitch.el-switch .el-switch__core,
/deep/ .el-switch .el-switch__label {
    width: 50px !important;    /*开关按钮的宽度大小*/
}

/deep/ .dialog .el-dialog{
  min-width: 570px;
}
</style>